package com.dove.tcpclient;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.InetSocketAddress;
import java.net.Socket;

public class Main2Activity extends AppCompatActivity {

    private Socket socket;

    private OutputStream os;
    private PrintWriter pw;

    private BufferedReader br;
    private InputStreamReader isr;
    private InputStream is;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
        new Thread(runnable).start();
    }

    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            TCPClient();
        }
    };

    protected void TCPClient(){
        try {
            //创建客户端Socket，指定服务器的IP地址和端口
//            socket = new Socket("192.16.201.80",8888);
            socket = new Socket();
            socket.connect(new InetSocketAddress("192.16.201.80",8888));
            //获取输出流，向服务器发送数据
            Log.i("dove","获取输出流");
            os = socket.getOutputStream();
            Log.i("dove","获取输出流----");
            pw = new PrintWriter(os);
            pw.write("我是客户端");
            pw.flush();

            //获取输入流，接收服务器发来的数据
            is = socket.getInputStream();
            isr = new InputStreamReader(is);
            br = new BufferedReader(isr);
            String data = null;
            //读取客户端数据
            while((data = br.readLine()) != null){
                Log.i("dove","客户端接收到服务器回应的数据：" + data);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        try {
            //关闭输出流
            socket.shutdownOutput();
            //关闭输入流
            socket.shutdownInput();
            //关闭资源
            br.close();
            isr.close();
            is.close();
            pw.close();
            os.close();
            socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
